<template>
  <div class="container">
    <el-cascader
        v-model="orgPath"
        :options="organizationOptions"
        :props="cascaderProps"
        placeholder="请选择组织机构"
        clearable
        style="width: 340px"
        @change="handleChange"
    />
      <el-input v-model="input" style="width: 7rem;margin-left: 2rem" placeholder="输入角色名称" />

      <el-select
        v-model="value1"
        placeholder="操作模块"
        style="width: 7rem;margin-left: 2rem"
      >
    <el-option
      v-for="item in options1"
      :key="item.value1"
      :label="item.label1"
      :value="item.value1"
    />
  </el-select>

      <el-date-picker
      v-model="timeValue"
      type="daterange"
      start-placeholder="开始时间"
      end-placeholder="结束时间"
      format="YYYY-MM-DD"
      date-format="YYYY/MM/DD"
      style="margin-left: 2rem;
      width: 15rem;"
    />
      <el-button style="width: 6rem;margin-left: 2rem;background-color: rgba(110, 78, 208, 0.1); border-color: #6f42c1; color: rgb(110, 78, 208);" type="primary" @click="filterUser">查询</el-button>
      <!-- 这里展示的是表格以及分页 -->
  <el-table :data="displayedData" style="width: 95%; margin-top: 3rem;"  class="auto-width-table">
<el-table-column label="序号">
  <template #default="{ row, $index }">
    <span v-if="row.operationLog ">{{ (currentPage - 1) * pageSize + $index + 1 }}</span>
  </template>
</el-table-column>

<el-table-column prop="role.roleName" label="用户名" >
  <template #default="{ row }">
    <span v-if="row.operationLog " style="color: black;">{{ row.operationLog.username }}</span>
    <span v-else style="color: transparent;">空</span>
  </template>
</el-table-column>
<el-table-column prop="role.roleName" label="姓名" >
  <template #default="{ row }">
    <span v-if="row.operationLog" style="color: black;">{{ row.operationLog.name }}</span>
    <span v-else style="color: transparent;">空</span>
  </template>
</el-table-column>  
<el-table-column prop="role.description" label="所属机构" >
  <template #default="{ row }">
    <span v-if="row.operationLog && row.operationLog.username == 'ruiboAdmin'" style="color: black;">中国铁塔股份有限公司安徽省分公司</span>
      <span v-if="row.operationLog && row.operationLog.username != 'ruiboAdmin'" style="color: black;">{{ row?.organizationName || "暂未分配组织"}}</span>
    <span v-else style="color: transparent;">空</span>
  </template>
</el-table-column>
<el-table-column prop="role.description" label="IP" >
  <template #default="{ row }">
    <span v-if="row.operationLog" style="color: black;">{{ row.operationLog.ip}}</span>
    <span v-else style="color: transparent;">空</span>
  </template>
</el-table-column>
<el-table-column prop="role.createTime" label="操作模块" >
  <template #default="{ row }">
    <span v-if="row.operationLog" style="color: black;">{{ row.operationLog.operationModel }}</span>
    <span v-else style="color: transparent;">空</span>
  </template>
</el-table-column>
<el-table-column prop="role.createTime" label="操作结果" >
  <template #default="{ row }">
    <span v-if="row.operationLog" style="color: black;">{{ row.operationLog.operationResult }}</span>
    <span v-else style="color: transparent;">空</span>
  </template>
</el-table-column>

<el-table-column prop="role.createTime" label="操作时间" >
  <template #default="{ row }">
    <span v-if="row.operationLog" style="color: black;">{{ row.operationLog.operationTime }}</span>
    <span v-else style="color: transparent;">空</span>
  </template>
</el-table-column>
</el-table>
<!-- 这里写分页页面 -->

<el-pagination
style="margin-top:2rem;"
v-model:current-page="currentPage"
v-model:page-size="pageSize"
:total="total"
layout="prev, pager, next, jumper"
:background="true"
@current-change="handleCurrentChange"
/>

  </div>
</template>

<script lang="ts" setup>
  import { ref ,onMounted ,nextTick,onUnmounted} from 'vue'
  import request from '@/utils/request';
  // 时间选择参数
  const timeValue = ref('')
  const value = ref('')
  const options = <any>ref([])   //全部组织     
  const value1 = ref('')
  const options1 = [
  {
    value1: '登录成功',
    label1: '登录成功',
  },
  {
    value1: '登录失败',
    label1: '登录失败',
  },
  {
    value1: '退出登录',
    label1: '退出登录',
  },
  ];  //全部角色 
  const tableData = ref([]); // 原始数据
  const displayedData = ref([]); // 当前页显示的数据
  const currentPage = ref(1); // 当前页码
  const pageSize = ref(10); // 每页条数
  const total = ref(0); // 总条数
  const input = ref('')
  const startTime = ref<any>('')
  const endTime = ref<any>('')

  function formatDate(date:any) {
const d = new Date(date);
const year = d.getFullYear();
const month = String(d.getMonth() + 1).padStart(2, '0');  // 月份从0开始，+1
const day = String(d.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}

const orgPath = ref<number[]>([]); // 用于原始路径绑定
    const selectedValue = ref<string>(''); // 最终展示用的值

const organizationOptions = ref<any[]>([]);

// 配置：emitPath: true 让我们拿到路径数组
const cascaderProps = {
  emitPath: true,
  checkStrictly: true
};

// 处理选择结果
const handleChange = (value: number[]) => {
  if (value.length === 1) {
    selectedValue.value = `${value[0]}` ; // 二级组织
  } else if (value.length === 2) {
    selectedValue.value = `${value[0]}-${value[1]}`; // 二级ID-三级ID
  }
};


// 请求并构建二级+三级组织数据
const getOrganizationOptions = () => {
  request.get('/user/getAllSecondaryOrganization').then((res1) => {
    const secondList = res1.data;
    request.get('/user/getAllThirdOrganization').then((res2) => {
      const thirdList = res2.data;

      const grouped = thirdList.reduce((acc: any, cur: any) => {
        if (!acc[cur.secondaryID]) acc[cur.secondaryID] = [];
        acc[cur.secondaryID].push({
          label: cur.organizationName,
          value: cur.id
        });
        return acc;
      }, {});

      const secondLevel = secondList.map((item: any) => ({
        label: item.organizationName,
        value: item.id,
        children: grouped[item.id] || []
      }));

      organizationOptions.value = secondLevel;
    });
  });
};


  const filterUser = () => {   
    if(formatDate(timeValue.value[0]) === "NaN-NaN-NaN"){
      startTime.value = null
    }else {
      startTime.value = formatDate(timeValue.value[0])
    }
    if(formatDate(timeValue.value[1]) === "NaN-NaN-NaN"){
      endTime.value = null
    }else {
      endTime.value = formatDate(timeValue.value[1])
    }
    
        request.post("/user/getOperationLogByCondition" ,{
          operationType:"login",
          organizationID:selectedValue.value || '',
          roleID:value1.value || '',
          username:input.value || '',
          operationModel:value1.value,
          startTime:startTime.value,
          endTime:endTime.value,
        }).then(
          (res)=>{
            if(res.status == 200){        
              displayedData.value = res.data
          }
          }
        )
  }

// 获取全部三级组织信息
const getAllThirdOrganization = () => {

    // 获取三级菜单数据
    request.get('/user/getAllThirdOrganization').then((response) => {
     if (response.data) {        
      options.value = response.data.map((item:any) => ({
          value :item.id,
          label :item?.organizationName,
      }))        
     }
    })
  .catch((error) => {
    console.error('获取组织数据失败:', error);
  });
};


// 获取全部日志信息
const getAllUser = () => {
const formData = new FormData();
  formData.append("operationType", "login"),
request.post('/user/getAllOperationLog',formData).then(
  (res)=>{
    if(res.data){
      
      tableData.value = res.data
      total.value = res.data.length;
      updateDisplayedData();
    }
  }
)
}

// 更新显示的数据
const updateDisplayedData = () => {
const start = (currentPage.value - 1) * pageSize.value;
const end = start + pageSize.value;
const currentData = tableData.value.slice(start, end);

// 填充空行以确保表格显示10行
displayedData.value = Array.from({ length: pageSize.value }, (_, index) => currentData[index] || {});
};

// 处理分页切换
const handleCurrentChange = (page: number) => {
currentPage.value = page;
updateDisplayedData();
};

const detectPageSize = () => {
  const width = window.innerWidth;
  pageSize.value = width <= 1800 ? 10 : 20; // ≤1200px 时显示10条，>1200px 时显示20条
  updateDisplayedData();
};

  onMounted(()=>{
    getOrganizationOptions()
    detectPageSize(); // 初始调用
    window.addEventListener('resize', detectPageSize); // 直接监听resize事件，不使用防抖
    getAllThirdOrganization()
    getAllUser()
  })
  onUnmounted(() => {
  window.removeEventListener('resize', detectPageSize); // 移除事件监听
});

</script>

<style scoped>
.container {
  width: 100%;
  height: calc(100vh - 100px);
  display: block;
  padding: 20px;
  box-sizing: border-box;
}
.container-head {
  display: flex
} 
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 16px;
}
.input-text {
  width: 20%;
  height: 2rem;
  line-height: 2rem;
  margin-left: 1rem;
}
.input-text1 {
  width: 10%;
  height: 2rem;
  line-height: 2rem;
  margin-left: 1rem;
}
.selected-tab {
background-color: #409eff;
color: white;
}
.empty-row {
background-color: #f5f7fa;
color: gray;
text-align: center;
}



/* 表格自动宽度样式 */
.auto-width-table {
  table-layout: fixed; /* 关键属性 */
}

/* 定义各列宽度比例 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(1)) { width: 5%; }  /* 序号 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(2)) { width: 12%; } /* 任务名称 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(3)) { width: 12%; } /* 任务类型 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(4)) { width: 12%; } /* 通信塔类型 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(5)) { width: 13%; }  /* 地市 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(6)) { width: 13%; }  /* 区县 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(7)) { width: 13%; }  /* 巡视人员 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(8)) { width: 25%; } /* 任务状态 */
/* 确保内容不溢出 */
.auto-width-table :deep(.cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .auto-width-table {
    min-width: 1000px; /* 在小屏幕上保持水平滚动 */
  }
}

</style>